package com.newly.driver.mqtt.service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.newly.api.business.feign.MQTTReceiverClient;
import com.newly.driver.mqtt.utils.MqttUtils;
import com.newly.driver.mqtt.utils.ReturnResult;
import com.newly.transfer.redis.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JsonParseException;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.UUID;

public class ReceiveService {

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    MQTTReceiverClient mqttReceiverClient;

    private String secret = "8c1db015-f067-42d8-b707-872ef2770ff4";

    public void messageArrived(String topic, JSONObject message, RedisUtils redisUtils, MQTTReceiverClient mqttReceiverClient) throws Exception {
        this.redisUtils = redisUtils;
        this.mqttReceiverClient = mqttReceiverClient;

        if (topic.indexOf("/command/request/request-id=0x10000001") >= 0) {
            mqttReceiverClient.register(topic, JSONUtil.toJsonStr(message));
        }
        else if(topic.indexOf("/event/up/event-id=0x10000001") >= 0){
            AsynReceiver asynReceiver = new AsynReceiver(topic,JSONUtil.toJsonStr(message),mqttReceiverClient);
            asynReceiver.start();
        }
    }

    /**
     * 网关注册
     *
     * @param message 消息数据
     */
    public void register(String topic, JSONObject message) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        JSONObject result = new JSONObject();
        JSONObject params = new JSONObject();
        try {
            params = JSONUtil.parseObj(message.getStr("params"));
        } catch (JsonParseException e) {
            throw e;
        }
        params = JSONUtil.parseObj(message.getStr("params"));
        String productKey = params.getStr("product-key");
        String cnonce = params.getStr("cnonce");
        String algorithm = params.getStr("algorithm");
        String sign = params.getStr("sign");
        long expires = Long.parseLong(params.getStr("expires"));

        //根据productKey，cnonce，secret生成sign
        String signText = productKey + ":" + cnonce + ":" + secret;
        MessageDigest messageDigest = MessageDigest.getInstance("SHA");
        byte[] cipherBytes = messageDigest.digest(signText.getBytes());
        String realSign = Base64.getEncoder().encodeToString(cipherBytes);

        //生成的sign比对请求中的sign,如果吻合则存库并返回成功
        if (realSign.equals(sign)) {

            UUID uuid = UUID.randomUUID();
            JSONObject data = new JSONObject();
            data.put("token", uuid.toString());
            result = ReturnResult.successRegister(message, data);
            MqttUtils.responseMessage(topic, result);
            redisUtils.set("mqtt"+productKey,uuid.toString(),expires);

            redisUtils.del("mqttGateway");

            String gatewayStr = redisUtils.get("mqttGateway",String.class);
            JSONArray gateway ;
            if(gatewayStr==null||"".equals(gatewayStr)){
                gateway = new JSONArray("[]");
            }else {
                gateway= JSONUtil.parseArray(gatewayStr);
            }
            if(!gateway.contains(productKey)) gateway.add(productKey);
            redisUtils.set("mqttGateway",JSONUtil.toJsonStr(gateway));
        } else {
            result = ReturnResult.error(message, "-32000");
            MqttUtils.responseMessage(topic, result);
        }
    }


}
